/*
 * RenzoImageManager.cpp
 *
 *  Created on: Aug 30, 2009
 *      Author: sonhua
 */

#include "RenzoImageManager.h"
#include "RenzoImage.h"
#include "Renzoderer.h"
#include "RenzoResourceManager.h"

namespace Renzo {

//ImageManager* ImageManager::imgManager = 0;
ImageManager::ImageManager() {	

}

ImageManager::~ImageManager() {
	// empty the images array
	for (ImageList::iterator i = images.begin(); i != images.end(); i++) {				
		//rzDel(i->second);
		Renzoderer::instance()->getResourceManager()->disposeObject(i->second);
	}
	images.clear();
}
/*
ImageManager::instance() {
	if (imgManager == 0) {
		imgManager = new ImageManager;
	}
	return imgManager;
}
*/
Image* ImageManager::load(String file) {
	ImageList::iterator i = images.find(file);
	if (i != images.end()) { // this image is already loaded 
		return i->second;
	} else {
		void* pixels;
		PixelFormat fmt;
		Size size;
		this->loadInternal(file, pixels, fmt, size);

		//Image* img = new Image(pixels, fmt, size, file);
		Image* img = (Image*)Renzoderer::instance()->getResourceManager()->createObject(ImageType);
		img->initialize(pixels, fmt, size, file);

		// house keeping in imageList
		images[file] = img;
		return img;
	}
}

void ImageManager::unload(Image *img) {
	ImageList::iterator i = images.find(img->getName());
	if (i != images.end()) { // this image is loaded and it is safe to unload
		images.erase(i);
	}
	//rzDel(img);
	Renzoderer::instance()->getResourceManager()->disposeObject(img);
}

}
